from __future__ import absolute_import
import logging
from forest.api import Command, get_tool

logger = logging.getLogger('forest.commands.EmbedInstaller')

class InstallForestService(Command):
    ''' Embeds the forest installer into the install_root. '''
    __register__ = 'commands.forest.InstallForestService'

    def run(self, config):
        installtree = config.get_install_root()
        # install service files

        if not config.get('forest.source', False):
            return

        # TODO: this doesnt really need a chroot, switch the systemd root
        with get_tool('system.chroot')(installtree):

            get_tool('files.write')('/etc/resolv.conf', '''nameserver 8.8.8.8\nnameserver 8.8.4.4''')

            systemd = get_tool('systemd.Systemd')('/')

            get_tool('systemd.new_target')('forest', systemd_default_target)

            for servicename, servicefile in forest_services.iteritems():
                curr_service = systemd.new(servicename, servicefile)
                curr_service.enable()

            # DONE: programmatic, this should be handled by systemctl install
            #get_tool('system.mkdir')('/etc/systemd/system/forest.service.wants')

            # systemd creates the directories needed when mounting
            get_tool('system.ln')('/lib/systemd/system/basic.target', '/etc/systemd/system/forest.target.wants/basic.target')
            get_tool('system.ln')('/lib/systemd/system/NetworkManager.service', '/etc/systemd/system/forest.target.wants/NetworkManager.service')
            get_tool('system.ln')('/lib/systemd/system/arp-ethers.service', '/etc/systemd/system/forest.target.wants/arp-ethers.service')
            get_tool('system.ln')('/lib/systemd/system/rsyslog.service', '/etc/systemd/system/forest.target.wants/rsyslog.service')

            # remove the default
            get_tool('system.remove')('/etc/systemd/system/getty.target.wants/getty@tty1.service')

            # set the default target
            get_tool('system.remove')('/etc/systemd/system/default.target.wants/*')
            get_tool('system.ln')('/etc/systemd/system/forest.target', '/etc/systemd/system/default.target')


systemd_default_target = '''# forest.target
[Unit]
Description=Forest Installer Target
Requires=basic.target
Conflicts=rescue.service rescue.target
After=basic.target rescue.service rescue.target NetworkManager.service
AllowIsolate=yes

[Install]
Alias=default.target
'''

systemd_default_service_file = '''# forest-installer.service
[Unit]
Description=Forest Install Service
# we need to wait for network manager so we can get stuff from the net
After=forest.target NetworkManager.service tmp.mount

[Service]
Type=oneshot
Environment=TERM=linux
WorkingDirectory=/
# override the build root. we use the mounted disk to download packages/headers/etc
ExecStart=/usr/bin/python -m forest.bin.install --verbose --debug --wait -b /installroot/tmp --loglevel DEBUG --logfile - --logfile /tmp/forest.log --reboot
Restart=no
RestartSec=0
TimeoutSec=0
StandardOutput=tty
TTYPath=/dev/tty1
TTYReset=no
TTYVHangup=no
TTYVTDisallocate=no
#KillSignal=SIGHUP

[Install]
WantedBy=forest.target
'''


systemd_console_service_file = '''# subclass of getty@.service
# autologin console for the forest
[Unit]
Description=Getty on tty2
BindTo=dev-tty2.device
After=dev-tty2.device

#systemd-user-sessions.service plymouth-quit-wait.service
#After=rc-local.service
After=forest.target

# If additional gettys are spawned during boot then we should make
# sure that this is synchronized before getty.target, even though
# getty.target didn't actually pull it in.
#Before=getty.target

[Service]
Type=oneshot
Environment=TERM=linux
ExecStart=/sbin/mingetty --autologin root tty2
Restart=yes
RestartSec=0
UtmpIdentifier=tty2
TTYPath=/dev/tty2
TTYReset=yes
TTYVHangup=yes
TTYVTDisallocate=yes
KillMode=process

# Unset locale for the console getty since the console has problems
# displaying some internationalized messages.
Environment=LANG= LANGUAGE= LC_CTYPE= LC_NUMERIC= LC_TIME= LC_COLLATE= LC_MONETARY= LC_MESSAGES= LC_PAPER= LC_NAME= LC_ADDRESS= LC_TELEPHONE= LC_MEASUREMENT= LC_IDENTIFICATION=

# Some login implementations ignore SIGTERM, so we send SIGHUP
# instead, to ensure that login terminates cleanly.
KillSignal=SIGHUP

[Install]
#Alias=forest.target.wants/forest-autologin.service
WantedBy=forest.target
'''

service_mnt_install = '''# mount /mnt/install
[Unit]
Description=mounting the installer
After=forest.target

[Mount]
What=/dev/disk/by-label/INSTALLER
Where=/mnt/install
Type=iso9660
Options=defaults
StandardOutput=tty
StandardError=tty

[Install]
WantedBy=forest.target
'''

service_tmp_tmpfs = '''# mount /tmp
[Unit]
Description=mounting the installer
After=forest.target

[Mount]
What=tmpfs
Where=/tmp
Type=tmpfs
Options=defaults,size=10%
StandardOutput=tty
StandardError=tty
[Install]
WantedBy=forest.target
'''

service_htop = '''# htop service
[Unit]
Description=htop on tty3
After=forest.target

[Service]
Type=simple
ExecStart=/usr/bin/htop
StandardInput=tty
StandardOutput=tty
TTYPath=/dev/tty3

[Install]
WantedBy=forest.target
'''

forest_services = {
    'mnt-install.mount': service_mnt_install,
    'tmp.mount': service_tmp_tmpfs,
    'forest.service': systemd_default_service_file,
    'forest-autologin.service': systemd_console_service_file,
    'htop.service': service_htop,
}
